package com.qidian.kk;

import java.util.Optional;

/**
 * @Author: KK
 * @DateTime: 2024/10/24 14:57
 **/
public class OptionalDemo01 {

    public static void main(String[] args) {

        // 在不确定返回值是否为空的情况下
        Optional<Author> authorOptional = Optional.ofNullable(getAuthor());
        authorOptional.ifPresent(author -> System.out.println(author.getName()));


        // 确定一个对象不是空**的则可以使用**Optional**的**静态方法of**来把数据封装成Optional对象。
        Optional<Object> optional = Optional.of(getAuthor());
        System.out.println(optional);


        /**
         * 安全正确的获取值
         */
        Optional<Author> authorOptional1 = Optional.ofNullable(getAuthor());
        Author author1 = authorOptional1.orElseGet(() -> new Author(1L, "亚索", 99, "一个从菜刀中明悟哲理的祖安人", null));
        System.out.println(author1);

        Optional<Author> authorOptional2 = Optional.ofNullable(null);
        try {
            Author author = authorOptional2.orElseThrow(() -> new RuntimeException("author为空"));
            System.out.println(author.getName());
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }


    private static Optional<Author> getAuthorsOptional() {
        // 数据初始化
        Author author = new Author(1L, "蒙多", 15, "一个从菜刀中明悟哲理的祖安人", null);

        return Optional.ofNullable(author);
    }
    private static Author getAuthor() {
        // 数据初始化
        return new Author(1L, "蒙多", 15, "一个从菜刀中明悟哲理的祖安人", null);
    }
}
